package com.ky.my.controller;

import com.ky.common.util.AliOssUtil;
import com.ky.common.vo.R;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * --- 天道酬勤 ---
 *
 * @author ZhaoTongTong
 * @date 2024/6/20
 * @desc -- 代码敲烂 月薪过万--
 */
public class UpLoadController {
    @PostMapping("/upload")
    public R uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            // 将MultipartFile转换为字节数组
            byte[] fileData = file.getBytes();

            // 直接调用工具类的静态方法进行上传
            String imageUrl = AliOssUtil.uploadByte("gp-kaoyan", generateObjectName(file), fileData);

            System.out.println(imageUrl);
            //将图片URL在？处进行分割
            String[] imageUrls = imageUrl.split("\\?");
            System.out.println(imageUrls[0]);
            return R.ok(imageUrls[0]); // 返回图片URL
        } catch (IOException e) {
            // 处理文件读取或转换异常
            throw new MultipartException("Failed to read or process the uploaded file", e);
        }
    }

    // 生成对象名，避免同名覆盖
    private String generateObjectName(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        return System.currentTimeMillis() + "_" + originalFilename;
    }
}


